<!--
 * @Descripttion: 新增员工
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-17 21:22:36
 -->
<template>
  <div class="app-container paddingT50">
    <affix>
      <div class="paddingLR20 clearfix">
        <el-card shadow="never" class="oper-btn-card">
          <div class="clearfix">
            <div class="fl">
              <el-button type="primary" size="medium" :loading="btnLoading.save" @click="btnSaveData">保存</el-button>
              <el-button type="default" size="medium" @click="btnCancle">取消</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </affix>
    <el-card shadow="never" class="border-radius-none margin-t2">
      <!-- dataObj: {{ dataObj }} -->
      <el-form
        ref="form"
        :model="dataObj"
        :rules="rules"
        label-position="right"
        label-width="100px"
        size="mini"
      >
        <h3>基础信息</h3>
        <el-divider />
        <div class="paddingTb20 w400">
          <el-form-item :label="`用户名:`" prop="username">
            <el-input v-model="dataObj.username" />
          </el-form-item>
          <el-form-item :label="`员工姓名`">
            <el-input v-model="dataObj.realName" />
          </el-form-item>
          <el-form-item label="性别:">
            <el-radio v-model="dataObj.sex" label="1">男</el-radio>
            <el-radio v-model="dataObj.sex" label="0">女</el-radio>
          </el-form-item>
          <el-form-item label="登录密码:" prop="password">
            <el-input v-model="dataObj.password" />
          </el-form-item>
          <el-form-item label="确认密码:" prop="passwordAgain">
            <el-input v-model="dataObj.passwordAgain" />
          </el-form-item>
        </div>
        <h3>权限管理</h3>
        <el-divider />
        <Permissions
          :id="id"
          ref="permissions"
          class="paddingTb20"
        />
        <h3>更多</h3>
        <el-divider />
        <div class="paddingTb20 w400">
          <el-form-item label="手机号:" prop="phone">
            <el-input v-model="dataObj.phone" />
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="dataObj.email" />
          </el-form-item>
          <el-form-item label="地址:">
            <el-input v-model="dataObj.address" />
          </el-form-item>
          <el-form-item label="状态:">
            <el-switch
              v-model="dataObj.status"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { isEmail, isTelOrPhone, validateUsername, validatePassword } from '@/utils/validate'
import { getDataById, saveData } from '@/api/bsd/employee.js'
import Affix from '@/components/Affix'
import Permissions from './permissions'
import clonedeep from 'clonedeep'

export default {
  name: 'EmployeeAdd',
  components: { Affix, Permissions },
  mixins: [oftenuse],
  props: {
    operation: {
      type: String,
      default: null,
      validator: (value) => {
        return ['add', 'update'].indexOf(value) !== -1
      }
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      dataObj: { status: '1' },
      originDataObj: {}, // 编辑状态初始值，用于对比是否修改
      optionsData: {},
      rules: {
        username: [
          { required: true, trigger: 'blur', validator: (rule, value, callback) => {
            if (this.id) {
              const oldValue = this.originDataObj.username
              if (oldValue === value) return callback()
              validateUsername(rule, value, callback)
            } else {
              validateUsername(rule, value, callback)
            }
          } }
        ],
        phone: [
          { validator: isTelOrPhone, trigger: 'blur' }
        ],
        password: [
          { trigger: 'blur', validator: (rule, value, callback) => {
            if (this.id) {
              if (!value || value === '') return callback()
              validatePassword(rule, value, callback)
            } else {
              validatePassword(rule, value, callback)
            }
          }
          }
        ],
        passwordAgain: [
          { validator: (rule, value, callback) => {
            const password = this.dataObj.password
            if (this.id) {
              if (!password || password === '') return callback()
              if (value !== password) {
                return callback(new Error('两次输入的密码不一致!'))
              }
              callback()
            } else {
              if (value !== password) {
                return callback(new Error('两次输入的密码不一致!'))
              }
              callback()
            }
          }, trigger: 'blur' }
        ],
        email: [
          { validator: isEmail, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.initData()
  },
  methods: {
    btnSaveData() {
      this.valiData().then(_ => {
        const params = this.getRequestData()
        this.setBtnLoading('save', true)
        this.saveData(params).then(_ => {
          this.setBtnLoading('save', false)
        })
      })
    },
    btnCancle() {
      this.jump2list()
    },
    // api
    getRequestData() {
      const permissionObj = this.$refs.permissions.getPermissionData()
      const roleList = this.$refs.permissions.getRolesData()
      const permissionDataStr = JSON.stringify(permissionObj)
      const params = {
        employee: this.dataObj,
        roleList,
        permissionData: { value: permissionDataStr }
      }
      return params
    },
    valiData() {
      const v1 = this.handleValid('form')
      const v2 = this.$refs.permissions.handleValid('form')
      return Promise.all([v1, v2])
    },
    saveData(params) {
      this.setBtnLoading('save', true)
      return saveData(params).then(res => {
        this.setBtnLoading('save', false)
        if (!res.data.flag) return
        this.$notify.success({ title: '保存成功！' })
        this.jump2list()
      }).catch(err => {
        this.$notify.error({ title: '保存异常！', message: err.message })
      })
    },
    jump2list() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'EmployeeList',
        params: { refresh: true }
      })
    },
    getData() {
      const store = this.dataObj
      return { store }
    },
    getDataById(id) {
      getDataById(id).then(res => {
        if (res.data.flag) {
          const data = res.data.data
          const { employee, permissionData, roleList } = data
          const permissionDataStr = permissionData ? permissionData.value || '{}' : '{}'
          const permissionDataObj = JSON.parse(permissionDataStr)
          this.dataObj = employee
          this.originDataObj = clonedeep(employee)
          this.$refs.permissions.setData({ permissionData: permissionDataObj, roleList })
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    },
    initData() {
      this.initOptionsData()
      const id = this.id
      if (id) this.initUpdateData(id)
    },
    initUpdateData(id) {
      this.getDataById(id)
    },
    initOptionsData() {

    }
  }
}
</script>

<style scoped>
.el-divider--horizontal{
  margin: 5px 0;
}
</style>
